<template>
  <div class="app-container card">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="任务名称" prop="jobName">
        <el-input
          v-model="queryParams.jobName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="任务分组" prop="jobGroup">
        <el-input
          v-model="queryParams.jobGroup"
          placeholder="请输入任务分组"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['system:job:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:job:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="jobList" @selection-change="handleSelectionChange" border>
      <el-table-column type="selection" width="45" align="center" />
      <el-table-column label="#" width="45" align="center">
        <template #default="scope">{{ scope.$index + 1 }}</template>
      </el-table-column>
      <el-table-column label="任务名称"  align="center" prop="jobName" />
      <el-table-column label="任务分组" align="center" prop="jobGroup" />
      <el-table-column label="执行方法" width="500" align="center" prop="invokeTarget" />
      <el-table-column label="cron表达式" align="center" prop="cronExpression" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <!-- 使用 el-switch 组件替代 el-tag -->
          <el-switch
            :value="scope.row.status === 0"
            @change="(val) => handleStatusChange(scope.row, val)"
          />
        </template>
      </el-table-column>

      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
              <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:job:edit']">修改</el-button>
              <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['system:job:remove']">删除</el-button>
          </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改定时任务对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="jobRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="任务名称" prop="jobName">
          <el-input v-model="form.jobName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务分组" prop="jobGroup">
          <el-input v-model="form.jobGroup" placeholder="请输入任务分组" />
        </el-form-item>
        <el-form-item label="执行方法" prop="invokeTarget">
          <el-input v-model="form.invokeTarget" type="textarea" placeholder="请输入执行方法" />
        </el-form-item>
        <el-form-item label="Cron表达式" prop="cronExpression">
          <el-input v-model="form.cronExpression" placeholder="请输入Cron表达式" />
        </el-form-item>
        <el-form-item label="排序码" prop="sort">
          <el-input-number
            v-model="form.sort"
            :min="0"
            controls-position="right"
          />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="5"
                    :maxlength="500"
                    show-word-limit
                    placeholder="请输入任务备注信息" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button :loading="buttonLoading" type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Job">
import { listJob, getJob, delJob, addJob, updateJob,updateJobStatus } from "@/api/monitor/job";

const { proxy } = getCurrentInstance();

const jobList = ref([]);
const open = ref(false);
const buttonLoading = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    jobName: undefined,
    jobGroup: undefined,
    status: undefined,
  },
  rules: {
    jobId: [
      { required: true, message: "任务id不能为空", trigger: "blur" }
    ],
    jobName: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    jobGroup: [
      { required: true, message: "任务分组不能为空", trigger: "blur" }
    ],
    invokeTarget: [
      { required: true, message: "执行方法不能为空", trigger: "blur" }
    ],
    cronExpression: [
      { required: true, message: "任务名称不能为空", trigger: "blur" }
    ],
    status: [
      { required: true, message: "状态 0正常 1暂停不能为空", trigger: "change" }
    ],
    sort: [
      { required: true, message: "排序码不能为空", trigger: "blur" }
    ],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询定时任务列表 */
function getList() {
  loading.value = true;
  listJob(queryParams.value).then(response => {
    jobList.value = response.data.records;
    console.log(jobList.value)
    total.value = response.data.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    jobId: null,
    jobName: null,
    jobGroup: null,
    invokeTarget: null,
    cronExpression: null,
    status: null,
    sort: 0,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark:null,
  };
  proxy.resetForm("jobRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.jobId);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加定时任务";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  loading.value = true
  reset();
  const _jobId = row.jobId || ids.value
  getJob(_jobId).then(response => {
    loading.value = false;
    form.value = response.data;
    open.value = true;
    title.value = "修改定时任务";
  });
}

/** 处理状态切换的方法 */
function handleStatusChange(row,flag) {
  row.status = flag ? 0 : 1;
  updateJobStatus(row).then(response => {
    proxy.$modal.msgSuccess( "操作成功");
  }).catch(error => {
    // 状态更新失败，恢复原状态
    row.status = row.status === 0 ? 1 : 0;
    proxy.$modal.msgError("操作失败");
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["jobRef"].validate(valid => {
    if (valid) {
      buttonLoading.value = true;
      if (form.value.jobId != null) {
        updateJob(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      } else {
        addJob(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        }).finally(() => {
          buttonLoading.value = false;
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _jobIds = row.jobId || ids.value;
  const count = Array.isArray(_jobIds) ? _jobIds.length : 1;
  proxy.$modal.confirm(`是否确认删除选中的${count}条定时任务？`).then(function() {
    loading.value = true;
    return delJob(_jobIds);
  }).then(() => {
    loading.value = true;
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {
  }).finally(() => {
    loading.value = false;
  });
}

getList();
</script>
